<template>
  <div class="home-container">
    <van-nav-bar title="标题" fixed>
      <template #left>
        <img src="../../assets/logo.png" alt="logo" class="logo" />
      </template>
      <template #right>
        <van-icon name="search" color="white" size='18' @click="$router.push('/search')" />
      </template>
    </van-nav-bar>

    <!-- 频道列表的标签页 -->
    <van-tabs v-model="active" sticky offset-top="1.22666667rem" :before-change="beforeTabsChange" @change="onTabsChange">
      <van-tab v-for="item in userChannel" :key='item.id' :title="item.name">
        <art-list :channel-id="item.id"></art-list>

      </van-tab>

    </van-tabs>

    <van-icon name="plus" size="16" class="plus" @click="show=true" />

    <van-popup v-model='show' :close-on-click-overlay='false' @close="isDel=false">
      <div class="popup-container">

        <!-- 弹出层的头部区域 -->
        <van-nav-bar title="频道管理">
          <template #right>
            <van-icon name="cross" size="14" color="white" @click="show = false" />
          </template>
        </van-nav-bar>

        <!-- 弹出层的主体区域 -->
        <div class="pop-body">
          <!-- 我的频道 -->
          <div class="my-channel-box">
            <div class="channel-title">
              <div>
                <span class="title-bold">已添加频道：</span>
                <span class="title-gray">{{isDel?'点击移除频道':'点击进入频道'}}</span>
              </div>
              <span class="btn-edit" @click="isDel=!isDel">{{isDel?'完成':'编辑'}}</span>
            </div>
            <!-- 我的频道列表 -->
            <van-row type="flex">
              <van-col span="6" v-for="(item,index) in userChannel" :key="item.id">
                <!-- 用户的频道 Item 项 -->
                <div class="channel-item van-hairline--surround" @click="onUserChannelClick(item,index)">
                  {{item.name}}
                  <!-- 删除的图标 -->
                  <van-badge color="transparent" class="cross-badge" v-if="isDel&&item.name!=='推荐'&&userChannel.length>2">
                    <template #content>
                      <van-icon name="cross" class="badge-icon" color="#cfcfcf" size="12" />
                    </template>
                  </van-badge>
                </div>
              </van-col>
            </van-row>
          </div>

          <!-- 分隔线 -->
          <div class="van-hairline--top sp-line"></div>

          <!-- 更多频道 -->
          <div class="more-channel-box">
            <div class="channel-title">
              <div>
                <span class="title-bold">可添加频道：</span>
                <span class="title-gray">点击添加频道</span>
              </div>
            </div>
            <!-- 更多频道列表 -->
            <van-row type="flex">
              <van-col span="6" v-for="item in moreChannels" :key="item.id">
                <div class="channel-item van-hairline--surround" @click="addChannel(item)">{{item.name}}</div>
              </van-col>
            </van-row>
          </div>
        </div>
      </div>

    </van-popup>

  </div>
</template>

<script>

import { getUserChannelApi, getAllChannelAPI, updateUserChannelAPI } from '@/api/homeAPI'
import ArtList from '@/components/ArtList/ArtList.vue'
// “频道名称”和“滚动条位置”之间的对应关系，格式 { '推荐': 211, 'html': 30, '开发者资讯': 890 }
const nameToTop = {}
export default {
  name: 'Home',
  data() {
    return {
      active: 0,
      userChannel: [],
      show: false,
      allChannel: [],
      isDel: false
    }
  },
  created() {
    this.initUserChannel()
    this.initAllChannel()
  },
  methods: {

    async initUserChannel() {
      const { data: res } = await getUserChannelApi()
      // console.log(res)
      if (res.message === 'OK') {
        this.userChannel = res.data.channels
      }
    },
    async initAllChannel() {
      const { data: res } = await getAllChannelAPI()
      if (res.message === 'OK') {
        this.allChannel = res.data.channels
      }
    },
    // 新增频道（形参 item 就是当前用户点击的频道信息对象）
    // 格式：{ id, name }
    addChannel(item) {
      this.userChannel.push(item)

      this.updataChannel()
    },
    async updataChannel(item) {
      const channels = this.userChannel.filter(item => item.name !== '推荐')
        .map((item, index) => {
          return {
            id: item.id,
            seq: index + 1
          }
        })

      const { data: res } = await updateUserChannelAPI(channels)
      if (res.message === 'OK') {
        console.log(res)
        this.$notify({ type: 'success', message: '更新成功', duration: 1000 })
      }
    },
    // tabs 发生切换之前，触发此方法
    beforeTabsChange() {
      // 把当前"频道名称"对应的"滚动条位置"记录到 nameToTop 对象中
      const name = this.userChannel[this.active].name

      nameToTop[name] = window.scrollY

      // return true 表示允许进行标签页的切换
      return true
    },
    onUserChannelClick(channel, index) {
      if (this.isDel) {
        if (channel.name === '推荐' || this.userChannel.length === 2) return

        this.userChannel = this.userChannel.filter(item => item.id !== channel.id)

        this.updataChannel()
      } else {
        this.active = index
        this.show = false
      }
    },
    // 当 tabs 切换完毕之后，触发此方法
    onTabsChange() {
      // 等 DOM 更新完毕之后，根据记录的"滚动条位置"，调用 window.scrollTo() 方法进行滚动
      this.$nextTick(() => {
        const name = this.userChannel[this.active].name
        window.scrollTo(0, nameToTop[name] || 0)
      })
    }

  },
  // 导航离开该组件的对应路由时调用
  // 可以访问组件实例 `this`
  beforeRouteLeave(to, from, next) {
    from.meta.top = window.scrollY
    next()
  },
  components: {
    ArtList
  },
  computed: {
    moreChannels() {
      return this.allChannel.filter(item => {
        const index = this.userChannel.findIndex(x => x.id === item.id)
        if (index === -1) {
          return true
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang='less' scoped>
.home-container {
  padding-top: 46px;
  padding-bottom: 50px;
}

.logo {
  height: 80%;
}
// 为 tabs 容器设置右 padding
/deep/ .van-tabs__wrap {
  padding-right: 36px;
  background-color: white;
}
.plus {
  position: fixed;
  top: 58px;
  right: 10px;
  z-index: 999;
}

.van-popup,
.popup-container {
  background-color: transparent;
  height: 100%;
  width: 100%;
}

.popup-container {
  display: flex;
  flex-direction: column;
}

.pop-body {
  flex: 1;
  overflow: scroll;
  padding: 8px;
  background-color: white;
}

.my-channel-box,
.more-channel-box {
  .channel-title {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    line-height: 28px;
    padding: 0 6px;
    .title-bold {
      font-weight: bold;
    }
    .title-gray {
      color: gray;
      font-size: 12px;
    }
  }
}

.btn-edit {
  border: 1px solid #a3a2a2;
  padding: 0 10px;
  line-height: 20px;
  height: 20px;
  border-radius: 6px;
  font-size: 12px;
}

.channel-item {
  font-size: 12px;
  text-align: center;
  line-height: 36px;
  background-color: #fafafa;
  margin: 6px;
}

.cross-badge {
  position: absolute;
  right: -3px;
  top: 0;
  border: none;
}

.sp-line {
  margin: 10px 0 20px 0;
}
</style>
